package com.fhx.core.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.fhx.core.R
import com.fhx.core.utils.EventBusManager
import com.fhx.core.utils.ScreenUtil
import com.fhx.core.utils.SharePreferencesUtil

abstract class BaseFragment : Fragment() {
    private var fragmentView : View? = null
    private var isInited = false//是否初始化过
    protected var mProgressView: View? = null
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        if(!isInited) {
            isInited = true
            main()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if(fragmentView == null) {
            fragmentView = layoutInflater.inflate(getLayoutId(), container, false)
        }
        initProgressView()
        return fragmentView
    }
    private fun initProgressView() {
        if (mProgressView == null) {
            val parent = fragmentView!!.parent as? ViewGroup
            mProgressView = layoutInflater.inflate(R.layout.loading_layout, parent, false)
            mProgressView?.setOnClickListener(null)
            showProgress(false)
            parent?.addView(mProgressView)
        }
    }

    fun showProgress(show: Boolean) {
        mProgressView?.visibility = if (show) View.VISIBLE else View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (fragmentView != null) {
            val parent = fragmentView!!.parent as? ViewGroup
            parent?.removeView(fragmentView)
        }
    }

    abstract fun getLayoutId(): Int

    open fun main() {

    }




    fun showToast(text: CharSequence) {
        Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBusManager.register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBusManager.unregister(this)
    }

}